package com.qf.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * test
 */
@Controller
public class TestController {

	@RequestMapping(value = "/checkWechat", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void checkWechat(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("called in checkWechat");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		/** 读取接收到的xml消息 */
		StringBuffer sb = new StringBuffer();
		InputStream is = request.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String s = "";
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		String xml =  sb.toString() ; //"<xml><ToUserName><![CDATA[gh_1fb11bb143c8]]></ToUserName><FromUserName><![CDATA[oxbR60-eCNeJ-1R5KxrMet7Nljus]]></FromUserName><CreateTime>1493374370</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content><MsgId>6413994080370458445</MsgId></xml>" ; //sb.toString(); // 次即为接收到微信端发送过来的xml数据
		
		String result = "1";
		/** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要把它直接返回 */
		String echostr = request.getParameter("echostr");
		if (echostr != null && echostr.length() > 1) {
			result = echostr;
		} else {
			// 正常的微信处理流程
			xml = xml == null || xml.length() < 1 ? "test" : xml ;
			System.out.println("xml:"+xml);
			result = new WechatProcess().processWechatMag(xml);
		}
		try {
			OutputStream os = response.getOutputStream();
			os.write(result.getBytes("UTF-8"));
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
